package com.jk.vehicle.mini.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * FastDFS文件上传下载工具类
 *
 * @author KangJian
 * @date 2018/7/19
 */
@Slf4j
public class FastDFSClient {

	/**
	 * 存储服务客户端
	 */
	private static StorageClient1 storageClient = null;

	/**
	 * 配置名称
	 */
	private static String CONF_FILENAME = null;

	static {
		try {
			// 获取环境变量
			// 复制配置文件到临时目录中
			InputStream is = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("fdfs_client.conf");
			String os = System.getProperty("os.name");
			if (os.toLowerCase().startsWith("win")) {
				CONF_FILENAME = System.getProperty("java.io.tmpdir") + "fdfs_client.conf";
			} else {
				CONF_FILENAME = System.getProperty("java.io.tmpdir") + File.separator + "fdfs_client.conf";
			}
			OutputStream fos = new FileOutputStream(CONF_FILENAME);
			byte[] bytes = new byte[1024];
			int i = is.read(bytes);
			while (i > 0) {
				fos.write(bytes, 0, i);
				i = is.read(bytes);
			}
			is.close();
			fos.close();
			log.info("FastDFS CONF_FILENAME:" + CONF_FILENAME);
			ClientGlobal.init(CONF_FILENAME);
			TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
			TrackerServer trackerServer = trackerClient.getConnection();
			if (trackerServer == null) {
				log.error("getConnection return null");
			}
			StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
			if (storageServer == null) {
				log.error("getStoreStorage return null");
			}
			storageClient = new StorageClient1(trackerServer, storageServer);
		} catch (Exception e) {
			log.error("FastDFS初始化异常", e);
		}
	}

	/**
	 * 上传文件
	 *
	 * @param file     文件对象
	 * @param fileName 文件名
	 * @return
	 */
	public static String[] uploadFile(File file, String fileName) {
		return uploadFile(file, fileName, null);
	}

	/**
	 * 上传文件
	 *
	 * @param file     文件对象
	 * @param fileName 文件名
	 * @param metaList 文件元数据
	 * @return
	 */
	public static String[] uploadFile(File file, String fileName, Map<String, String> metaList) {
		try {
			byte[] buff = IOUtils.toByteArray(new FileInputStream(file));
			NameValuePair[] nameValuePairs = null;
			if (metaList != null) {
				nameValuePairs = new NameValuePair[metaList.size()];
				int index = 0;
				for (Iterator<Map.Entry<String, String>> iterator = metaList.entrySet().iterator(); iterator
						.hasNext(); ) {
					Map.Entry<String, String> entry = iterator.next();
					String name = entry.getKey();
					String value = entry.getValue();
					nameValuePairs[index++] = new NameValuePair(name, value);
				}
			}
			return storageClient.upload_file(buff, fileName, nameValuePairs);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 获取文件元数据
	 *
	 * @param fileId 文件ID
	 * @return
	 */
	public static Map<String, String> getFileMetadata(String groupname, String fileId) {
		try {
			NameValuePair[] metaList = storageClient.get_metadata(groupname, fileId);
			if (metaList != null) {
				HashMap<String, String> map = new HashMap<String, String>();
				for (NameValuePair metaItem : metaList) {
					map.put(metaItem.getName(), metaItem.getValue());
				}
				return map;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 删除文件
	 * @param groupName 组名 如：group1
	 * @param fileId 不带组名的路径名称 如：M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
	 * @return -1失败,0成功
	 */
	public static int deleteFile(String groupName, String fileId) {
		try {
			return storageClient.delete_file(groupName, fileId);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return -1;
	}

	/**
	 * 下载文件
	 *
	 * @param fileId  文件ID（上传文件成功后返回的ID）
	 * @param outFile 文件下载保存位置
	 * @return
	 */
	public static int downloadFile(String groupName, String fileId, File outFile) {
		FileOutputStream fos = null;
		try {
			byte[] content = storageClient.download_file(groupName, fileId);
			fos = new FileOutputStream(outFile);
			InputStream ips = new ByteArrayInputStream(content);
			IOUtils.copy(ips, fos);
			return 0;
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					log.error(e.getMessage());
				}
			}
		}
		return -1;
	}

	/**
	 * 上传文件
	 *
	 * @param buff 文件对象流
	 * @param fileName 文件名
	 * @return
	 */
	public static String uploadFile(byte[] buff, String fileName) {
		return uploadFile(buff, fileName, null);
	}

	/**
	 * 上传文件
	 *
	 * @param buff 文件对象流
	 * @param fileName 文件名
	 * @param metaList 文件元数据
	 * @return
	 */
	public static String uploadFile(byte[] buff, String fileName, Map<String, String> metaList) {
		try {
			NameValuePair[] nameValuePairs = null;
			if (metaList != null) {
				nameValuePairs = new NameValuePair[metaList.size()];
				int index = 0;
				for (Iterator<Map.Entry<String, String>> iterator = metaList.entrySet().iterator(); iterator
						.hasNext(); ) {
					Map.Entry<String, String> entry = iterator.next();
					String name = entry.getKey();
					String value = entry.getValue();
					nameValuePairs[index++] = new NameValuePair(name, value);
				}
			}
			return storageClient.upload_file1(buff, FileUtil.getExtensionName(fileName), nameValuePairs);
		} catch (Exception e) {
			log.error("uploadFile error by FastDFSClient,exception:{}", e);
		}
		return null;
	}


	/**
	 * 下载文件
	 *
	 * @param fileId  文件ID（上传文件成功后返回的ID）
	 * @return
	 */
	public static byte[] downloadFile(String fileId) {
		try {
			byte[] content = storageClient.download_file1(fileId);
			return content;
		} catch (Exception e) {
			log.error("downloadFile error by FastDFSClient,exception:{}", e);
		}
		return null;
	}


	/**
	 * Description:获取文件信息
	 *
	 * @param fileId
	 * @return
	 * @see
	 */
	public static FileInfo getFileInfo(String fileId) {

		try {
			FileInfo fileInfo = storageClient.get_file_info1(fileId);
			return fileInfo;
		} catch (Exception e) {
			log.error("getFileInfo error by FastDFSClient,exception:{}", e);
		}
		return null;
	}

	/**
	 * 获取文件元数据
	 *
	 * @param fileId 文件ID
	 * @return
	 */
	public static Map<String, String> getFileMetadata(String fileId) {
		try {
			NameValuePair[] metaList = storageClient.get_metadata1(fileId);
			if (metaList != null) {
				HashMap<String, String> map = new HashMap<String, String>();
				for (NameValuePair metaItem : metaList) {
					map.put(metaItem.getName(), metaItem.getValue());
				}
				return map;
			}
		} catch (Exception e) {
			log.error("getFileMetadata error by FastDFSClient,exception:{}", e);
		}
		return null;
	}

	/**
	 * 删除文件
	 *
	 * @param fileId
	 *            文件ID
	 * @return 删除失败返回-1，否则返回0
	 */
	public static int deleteFile(String fileId) {
		try {
			return storageClient.delete_file1(fileId);
		} catch (Exception e) {
			log.error("deleteFile error by FastDFSClient,exception:{}", e);
		}
		return -1;
	}


	/**
	 * 测试main方法
	 * @param args
	 */
	//	public static void main(String[] args) {
	//		OutputStream fos = null;
	//		try {
	//			String fileId = "group1/M00/00/00/wKgFultRiPSARrO1AAFJfa3Zpi8004.jpg";
	//			FileInfo fileInfo = FastDFSClient.getFileInfo("group1/M00/00/00/wKgFultRiPSARrO1AAFJfa3Zpi8004.jpg");
	//			if (fileInfo != null) {
	//				log.info("result:{}", JSON.toJSONString(fileInfo));
	//				Map<String, String> fileMetadata = FastDFSClient
	//						.getFileMetadata("group1/M00/00/00/wKgFultRiPSARrO1AAFJfa3Zpi8004.jpg");
	//				log.info("fileMetadata:{}", JSON.toJSONString(fileMetadata));
	//				byte[] content = FastDFSClient.downloadFile(fileId);
	//				fos = new FileOutputStream(new File("/data/test.jpg"));
	//				InputStream ips = new ByteArrayInputStream(content);
	//				IOUtils.数据和结构(ips, fos);
	//			}
	//		} catch (IOException e) {
	//			log.error(e.getMessage());
	//		} finally {
	//			if (fos != null) {
	//				try {
	//					fos.close();
	//				} catch (IOException e) {
	//					log.error(e.getMessage());
	//				}
	//			}
	//		}
	//	}
}
